package com.dzf.dao;

import com.dzf.entity.Blog;
import com.dzf.entity.BlogCont;
import com.dzf.entity.Discuss;
import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DiscussDao {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    BlogDao blogDao;

    public boolean addDiscuss(Discuss discuss){

        BlogCont blogCont = blogDao.findById(discuss.getBlogId());
        Blog blog = blogCont.getBlog();
        blog.setReview(blog.getReview()+1);
        blogCont.setBlog(blog);
        blogDao.amend(blogCont);

        Discuss discuss1 = mongoTemplate.save(discuss);
        return discuss1!=null?true:false;
    }

    public Boolean delDiscuss(Discuss did)
    {
        BlogCont blogCont = blogDao.findById(did.getBlogId());
        Blog blog = blogCont.getBlog();
        blog.setReview(blog.getReview()-1);
        blogCont.setBlog(blog);
        blogDao.amend(blogCont);

        DeleteResult result = mongoTemplate.remove(new Query(Criteria.where("id").is(did.getId())),Discuss.class);
        return result!=null?true:false;
    }

    public Map<String, Object> findByDis(String blogid, int pagenum)
    {

        Map<String, Object> map = new HashMap<>();
        Query query = new Query();
        query.addCriteria(Criteria.where("blogId").is(blogid));
        query.addCriteria(Criteria.where("level").is(0));
        int total = (int) mongoTemplate.count(query, Discuss.class);
        map.put("total",total);
        query.with(Sort.by(Sort.Order.asc("createTime")));
        query.skip(pagenum).limit(10);

        List<Discuss> list = mongoTemplate.find(query, Discuss.class);
        map.put("list",list);
        return map;
    }
    public List<Discuss> findByDislevel(String disid,int level)
    {
        Query query = new Query();
        query.addCriteria(Criteria.where("disid").is(disid).and("level").is(level));
        query.with(Sort.by(Sort.Order.asc("createTime")));
        List<Discuss> list = mongoTemplate.find(query, Discuss.class);
        return list;
    }

    //用户查看自己发表的评论
    public Map<Object, Object> findByUserDis(String uid, int pagenum, int num)
    {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(uid));
        int count = (int) mongoTemplate.count(query,Discuss.class);
        query.skip(pagenum).limit(10);
        List<Discuss> list = mongoTemplate.find(query, Discuss.class);

        Map<Object, Object> map = new HashMap<>();
        map.put("total",count);
        map.put("list",list);

        return map;
    }
}
